﻿using DevExpress.Utils;
using MDIDemo.Model;
using MDIDemo.PublicClass;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MDIDemo.PublicClass.Class_DataBaseContent;

namespace DevMy.Vou
{
    public partial class Form_Eqiupment : Form_BaseAlone
    {
        public Form_Eqiupment(string FormText)
        {
            InitializeComponent();
            SetComponent(FormText);
        }
        private WaitDialogForm waitDialogForm;
        private Class_MySqlDataBase class_MySqlDataBase;
        private void SetComponent(string FormText)
        {
            base.SetComponent(FormText, "I0006");
            base.SetGridDataSource(null);
            base.GetGridPage().PageSize = 50;
            base.EnableViewButton(false);
            base.EnableOutButton(false);

            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_DataBaseConDefault class_DataBaseConDefault = new Class_DataBaseConDefault();
            class_DataBaseConDefault = class_PublicMethod.FromXmlToDefaultValueObject<Class_DataBaseConDefault>("DataBaseDefaultValues");

            class_MySqlDataBase = new Class_MySqlDataBase(class_DataBaseConDefault.dataSourceUrl
                , class_DataBaseConDefault.dataBaseName
                , class_DataBaseConDefault.dataSourceUserName
                , class_DataBaseConDefault.dataSourcePassWord
                , class_DataBaseConDefault.Port);
        }
        public override int AddData()
        {
            int index = -1;
            Form_EquipmentBase form_EquipmentBase = new Form_EquipmentBase();
            form_EquipmentBase.SetWinType(1);
            form_EquipmentBase.id = null;
            form_EquipmentBase.Ini();
            form_EquipmentBase.Text = this.Text;
            if (form_EquipmentBase.ShowDialog() == DialogResult.OK)
            {
                string Sql = string.Format(@"insert into vou_equipment
                        (id
                        ,equipmentName
                        , factoryName
                        , ip
                        , remark
                        , equipmentType
                        , port
                        , sensorCount
                        , address) values
                ('{0}','{1}', '{2}','{3}','{4}', '{5}',{6},{7},{0}) "
                        , form_EquipmentBase.equipmentModel.id
                        , form_EquipmentBase.equipmentModel.equipmentName
                        , form_EquipmentBase.equipmentModel.factoryName
                        , form_EquipmentBase.equipmentModel.ip
                        , form_EquipmentBase.equipmentModel.remark
                        , form_EquipmentBase.equipmentModel.equipmentType
                        , form_EquipmentBase.equipmentModel.port
                        , form_EquipmentBase.equipmentModel.sensorCount
                    );
                index = class_MySqlDataBase.ExecuteSql(Sql);
                class_MySqlDataBase.ExecuteSql(string.Format("Delete FROM vou_equipmentparamer WHERE mainId='{0}'"
                    , form_EquipmentBase.equipmentModel.id));
                AddSensor(form_EquipmentBase.equipmentModel.id, form_EquipmentBase.equipmentModel.sensorCount);
                for (int i = 0; i < 12; i++)
                {
                    Sql = string.Format(@"INSERT INTO vou_equipmentparamer(sensorNo,mainId
                        ,paramName
                        ,chinaName
                        ,sortNo
                        ,paramType
                        ,defaultValue
                        ,beginValue
                        ,endValue
                        ,valueType)
                        SELECT
                        {1},'{0}'
                        ,paramName
                        ,chinaName
                        ,sortNo
                        ,paramType
                        ,defaultValue
                        ,beginValue
                        ,endValue
                        ,valueType
                        FROM `vou_equipmentparamerdefault`
                        ORDER BY sortNo"
                        , form_EquipmentBase.equipmentModel.id
                        , i + 1);
                    index += class_MySqlDataBase.ExecuteSql(Sql);
                }
            }
            form_EquipmentBase.Dispose();
            return index;
        }
        public override int EditData(object id)
        {
            int index = -1;
            Form_EquipmentBase form_EquipmentBase = new Form_EquipmentBase();
            form_EquipmentBase.SetWinType(0);
            form_EquipmentBase.id = id.ToString();
            form_EquipmentBase.Ini();
            form_EquipmentBase.Text = this.Text;
            if (form_EquipmentBase.ShowDialog() == DialogResult.OK)
            {
                string Sql = string.Format(@"update vou_equipment
                Set    equipmentName = '{1}'
                        , factoryName = '{2}'
                        , ip = '{3}'
                        , remark = '{4}'
                        , equipmentType = '{5}'
                        , port = {6}
                        , sensorCount = {7}
                where id = '{0}'"
                        , form_EquipmentBase.equipmentModel.id
                        , form_EquipmentBase.equipmentModel.equipmentName
                        , form_EquipmentBase.equipmentModel.factoryName
                        , form_EquipmentBase.equipmentModel.ip
                        , form_EquipmentBase.equipmentModel.remark
                        , form_EquipmentBase.equipmentModel.equipmentType
                        , form_EquipmentBase.equipmentModel.port
                        , form_EquipmentBase.equipmentModel.sensorCount
                    );
                index = class_MySqlDataBase.ExecuteSql(Sql);
                AddSensor(form_EquipmentBase.equipmentModel.id, form_EquipmentBase.equipmentModel.sensorCount);
            }
            form_EquipmentBase.Dispose();
            return index;
        }
        public override void ViewData(object id)
        {
            MessageBox.Show(id.ToString());
        }

        public override int DeleteData(object id)
        {
            DeleteSensor(id.ToString());
            DeleteParamer(id.ToString());
            string Sql = string.Format("delete from vou_equipment where id = '{0}'", id.ToString());
            class_MySqlDataBase.ExecuteSql(string.Format("Delete FROM vou_equipmentparamer WHERE mainId='{0}'", id));

            return class_MySqlDataBase.ExecuteSql(Sql);
        }

        public override void ToExcel(SaveFileDialog saveFileDialog)
        {
            const string FileName = "设备基本信息";
            string DataBaseFileName = string.Format("{0}{1}"
                , FileName
                , System.DateTime.Now.ToString("yyyyMMdd"));
            SaveFileDialog SaveFileDialog = new SaveFileDialog();
            SaveFileDialog.FileName = DataBaseFileName;
            SaveFileDialog.Filter = "EXCEL|*.xlsx";
            SaveFileDialog.Title = string.Format("导出{0}", FileName);
            if (SaveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Class_ToExcel class_ToExcel = new Class_ToExcel();
                ArrayList SheetNameArray = new ArrayList();
                ArrayList SheetTitleArray = new ArrayList();
                ArrayList FieldTitleArray = new ArrayList();
                ArrayList AveFieldNameList = new ArrayList();
                bool IsTotal = false;
                bool IsAverage = false;
                bool IsHeader = false;
                string LeftFieldName = null;
                string ExcelFileName = DataBaseFileName;
                string SumFieldNameList = null;
                DataSet ExcelDataSet = new DataSet();

                #region 自定义
                SheetNameArray.Add(FileName);
                SheetTitleArray.Add(FileName);
                DataTable dataTable = new DataTable();
                dataTable = class_MySqlDataBase.GetEquipmentNoPage(1, 0);
                ExcelDataSet.Tables.Add(dataTable);
                #endregion

                class_ToExcel._GiveYouExcel(
                    SheetNameArray
                    , SheetTitleArray
                    , IsTotal
                    , ExcelFileName
                    , FieldTitleArray
                    , SumFieldNameList
                    , IsAverage
                    , AveFieldNameList
                    , IsHeader
                    , LeftFieldName
                    , ExcelDataSet);

                ExcelDataSet.Dispose();
                if (SheetNameArray.Count > 0)
                    SheetNameArray.Clear();
                if (SheetTitleArray.Count > 0)
                    SheetTitleArray.Clear();
                if (FieldTitleArray.Count > 0)
                    FieldTitleArray.Clear();
                if (AveFieldNameList.Count > 0)
                    AveFieldNameList.Clear();
            }

        }

        public override void ToWord(SaveFileDialog saveFileDialog)
        {
            base.ToWord(saveFileDialog);
        }

        private string GetDataBaseContent()
        {
            try
            {
                string DataBaseFileName = string.Format("{0}{1}"
                    , "设备基本信息"
                    , System.DateTime.Now.ToString("yyyyMMdd"));
                SaveFileDialog SaveFileDialog = new SaveFileDialog();
                SaveFileDialog.FileName = DataBaseFileName;
                SaveFileDialog.Filter = "EXCEL|*.xlsx";
                SaveFileDialog.Title = "生成数据库说明书";
                if (SaveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Class_ToExcel class_ToExcel = new Class_ToExcel();
                    Class_DataBaseContent class_DataBaseContent = new Class_DataBaseContent();
                    class_DataBaseContent.DataBaseFileName = DataBaseFileName;
                    //1：得到所有用户列表信息，包括：表名、表注释；
                    List<Class_TableInfo> class_TableInfos = new List<Class_TableInfo>();
                    //class_TableInfos = GetUseTableList(null);
                    //if ((class_TableInfos != null) && (class_TableInfos.Count > 0))
                    //{
                    //    #region 得到所有表信息
                    //    DataTable dataTable = new DataTable("TableInfo");
                    //    DataColumn TableIndex = new DataColumn("TableIndex", typeof(int));
                    //    DataColumn TableName = new DataColumn("TableName", typeof(string));
                    //    DataColumn TableComment = new DataColumn("TableComment", typeof(string));
                    //    dataTable.Columns.Add(TableIndex);
                    //    dataTable.Columns.Add(TableName);
                    //    dataTable.Columns.Add(TableComment);

                    //    int TableCount = 1;
                    //    foreach (Class_TableInfo class_TableInfo in class_TableInfos)
                    //    {
                    //        DataRow newRow = dataTable.NewRow();
                    //        newRow["TableIndex"] = TableCount++;
                    //        newRow["TableName"] = class_TableInfo.TableName;
                    //        newRow["TableComment"] = class_TableInfo.TableComment;
                    //        TableCount++;
                    //        dataTable.Rows.Add(newRow);
                    //    }
                    //    Class_SheetContent class_SheetContent = new Class_SheetContent();
                    //    class_SheetContent.dataTable = dataTable;
                    //    class_SheetContent.FieldTitleList.Add("序号");
                    //    class_SheetContent.FieldTitleList.Add("表名");
                    //    class_SheetContent.FieldTitleList.Add("注释");
                    //    class_SheetContent.LeftFieldNameList.Add("TableComment");
                    //    class_SheetContent.SheetName = "用户表";
                    //    class_SheetContent.SheetTitle = "用户表";
                    //    class_SheetContent.TableContent = string.Format("{0}库的所有用户表", this.DataBaseName);
                    //    class_DataBaseContent.class_SheetContents.Add(class_SheetContent);
                    //    #endregion

                    //    2：根据表名，得到表字段信息；
                    //    TableCount = 1;
                    //    foreach (Class_TableInfo class_TableInfo in class_TableInfos)
                    //    {
                    //        dataTable = new DataTable(class_TableInfo.TableName + TableCount.ToString());
                    //        dataTable = _GetTableStruct(class_TableInfo.TableName);
                    //        Class_SheetContent class_SheetContentRow = new Class_SheetContent();
                    //        class_SheetContentRow.dataTable = dataTable;
                    //        class_SheetContentRow.FieldTitleList.Add("字段名");
                    //        class_SheetContentRow.FieldTitleList.Add("注释");
                    //        class_SheetContentRow.FieldTitleList.Add("字段类型");
                    //        class_SheetContentRow.FieldTitleList.Add("字段长度");
                    //        class_SheetContentRow.FieldTitleList.Add("默认值");
                    //        class_SheetContentRow.FieldTitleList.Add("是否可为空");
                    //        class_SheetContentRow.FieldTitleList.Add("主键");
                    //        class_SheetContentRow.FieldTitleList.Add("自增");
                    //        class_SheetContentRow.LeftFieldNameList.Add("FieldRemark");
                    //        class_SheetContentRow.SheetName = TableCount.ToString();
                    //        class_SheetContentRow.SheetTitle = class_TableInfo.TableName;
                    //        class_SheetContentRow.TableContent = class_TableInfo.TableComment;
                    //        class_DataBaseContent.class_SheetContents.Add(class_SheetContentRow);
                    //        TableCount++;
                    //    }
                    //    dataTable.Dispose();
                    //    DataBaseFileName = class_ToExcel.GetDataBaseContent(class_DataBaseContent, SaveFileDialog.FileName);
                    //}
                    //else
                    //    DataBaseFileName = null;
                }
                else
                {
                    DataBaseFileName = null;
                }
                SaveFileDialog.Dispose();
                return DataBaseFileName;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public override void Finder(int PageNo)
        {
            waitDialogForm = new WaitDialogForm("正在玩命加载中......", "温馨提示");

            DataSet dataSet = this.GetFinder(PageNo, base.GetGridPage().PageSize, this.textEdit1.Text);
            base.SetGridDataSource(dataSet.Tables[0]);
            base.GetGridPage().SetRowCount(int.Parse(dataSet.Tables[1].Rows[0][0].ToString()));
            waitDialogForm.Close();
        }
        private void DeleteParamer(string MainId)
        {
            class_MySqlDataBase.ExecuteSql(string.Format(@"Delete From vou_equipmentparamer
                Where mainId='{0}'", MainId));
        }
        private void DeleteSensor(string MainId)
        {
            class_MySqlDataBase.ExecuteSql(string.Format(@"Delete From inf_sensor
                Where mainId='{0}'", MainId));
        }
        private void AddSensor(string MainId, int sensorCount)
        {
            DeleteSensor(MainId);
            for (int i = 0; i < sensorCount; i++)
            {
                string Sql = string.Format(@"Insert Into inf_sensor(id,sortNo,mainId,sensorType)
                    Values ('{0}',{1},'{2}',{3})"
                    , MainId + "_" + (i + 1).ToString()
                    , i + 1
                    , MainId
                    , i < 6 ? 2 : 1);
                class_MySqlDataBase.ExecuteSql(Sql);
            }
        }
        private DataSet GetFinder(int PageNo, int PageSize, string Address)
        {
            string SelectSql = "SELECT *";
            string FormSql = "FROM vou_equipment";
            string WhereSql = null;
            string GroupSql = null;
            string HavingSql = null;
            string OrderSql = "ORDER BY ip";
            string TotalFieldName = "*";

            if (Address != null && Address.Trim().Length > 0)
            {
                WhereSql = string.Format("Where id = '{0}'", Address.Trim());
            }

            PageSqlModel pageSqlModel = class_MySqlDataBase.GetSql(SelectSql
            , FormSql
            , WhereSql
            , GroupSql
            , HavingSql
            , OrderSql
            , PageNo
            , PageSize
            , TotalFieldName);

            return class_MySqlDataBase.GetPageDataSet(pageSqlModel);
        }

        private void textEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                Finder(base.GetGridPage().GetPageNo());
            }
        }

        private void Form_Eqiupment_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (waitDialogForm != null)
            {
                waitDialogForm.Dispose();
            }
            class_MySqlDataBase.CloseSqlConnection();
        }
    }
}
